﻿using MassTransit;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Tiens.NotificationHub.Core.Consumers;
using Tiens.NotificationHub.Core.Options;
using Tiens.NotificationHub.Core.Services;
using Tiens.NotificationHub.Services;
using Tiens.NotificationHub.WebHost.Options;

namespace Tiens.NotificationHub.WebHost.Extensions
{
    public static class SeviceCollectionExtensions
    {
        public static IServiceCollection AddEventBus(this IServiceCollection services, IConfiguration configuration)
        {
            var massTransitOption = configuration.GetSection(nameof(MassTransitOptions))
                .Get<MassTransitOptions>();

            services.AddMassTransit(x =>
            {
                x.AddConsumers(typeof(NotifyingAllUsersWithAppIdConsumer).Assembly);
                x.SetKebabCaseEndpointNameFormatter();
                x.UsingRabbitMq((context, cfg) =>
                {
                    cfg.ConfigureEndpoints(context);
                    cfg.Host(massTransitOption.Host, massTransitOption.Port, massTransitOption.VirtualHost, h =>
                        {
                            h.Username(massTransitOption.Username);
                            h.Password(massTransitOption.Password);
                        }
                    );
                });
            });

            return services.AddMassTransitHostedService();
        }

        public static IServiceCollection AddSwaggerUI(this IServiceCollection services)
        {
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo()
                {
                    Title = "Notification-Hub HTTP API",
                    Version = "v1",
                    Description = "The Notification-Hub HTTP API"
                });

                options.DocInclusionPredicate((docName, description) => true);

            });

            return services;
        }

        public static IServiceCollection AddSmtpMail(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddOptions<SmtpOptions>()
               .Configure(configuration.GetSection(nameof(SmtpOptions)).Bind);

            services.AddScoped<ISmtpMailService, SmtpMailService>();

            return services;
        }
    }
}
